<template>
  <div>
    <TopFilter ref="TopFilter" :list="topFilterList" :cols="3" labelWidth="100" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :rowstyles="rowstyles"
      :cellstyles="cellstyles"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="DataHandle"
      columnsRef="potenCus_customer_customerFollowInfo_follow_01"
    >
      <template slot="controls">
        <el-button type="text" disabled>黄色代表当日未完成</el-button>
        <el-button type="text" disabled>红色代表逾期</el-button>
        <multiuse-button size="small" type="primary" :click="exportHandle" auth-mark="/api/clue/actioned/exportFollowByExcel">导出</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <followModal :type="handleType" :rowData="formData" @close="closeHandler" @fatherClose="fatherClose" />
    </BaseDialog>
    <Drawer :visible.sync="visibleClues" :title="dialogTitle" width="80%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <cluesModel :type="handleType" :rowData="formData" @close="closeHandler_clues" />
    </Drawer>
    <Drawer :visible.sync="visibleDetail" :title="dialogTitle" width="80%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" class="father">
      <div class="father" v-if="this.dataType == 10461001">
        <div class="son">
          <!-- <el-button size="small" type="primary" @click="editClick" :disabled="formData.intentLevel === 15191007 || formData.intentLevel === 15191006">编辑</el-button> -->
          <!-- <el-button size="small" type="primary" @click="followClick" :disabled="formData.intentLevel === 15191007 || formData.intentLevel === 15191006 || formData.actionId == null">跟进</el-button> -->
          <multiuse-button
            size="small"
            type="primary"
            :disabled="formData.intentLevel === 15191007 || formData.intentLevel === 15191006"
            :click="editClick"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/potenCus/updatePotenInfo"
            >编辑</multiuse-button
          >
          <multiuse-button
            size="small"
            type="primary"
            :disabled="formData.intentLevel === 15191007 || formData.isComplete == 10041001 || formData.intentLevel === 15191006 || formData.actionId == null"
            :click="followClick"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/actioned/updateFollowRecord"
            >跟进</multiuse-button
          >
          <el-button size="small" type="primary" @click="driveClick" :disabled="formData.intentLevel === 15191007 || formData.intentLevel === 15191006 || formData.haveTestDrive === true"
            >试驾</el-button
          >
          <el-button size="small" type="primary" @click="offerClick" :disabled="formData.intentLevel === 15191007 || formData.intentLevel === 15191006">报价</el-button>
          <!-- <el-button size="small" type="primary" @click="orderClick" :disabled="formData.intentLevel === 15191007 || formData.intentLevel === 15191006">下单</el-button> -->
        </div>
      </div>
      <!-- <div class="father" v-else>
        <div class="son">
          <el-button size="small" type="primary" @click="editClick">编辑</el-button>
        </div>
      </div>-->
      <Detail ref="Detail" :type="handleType" :rowData="formData" @close="closeHandler_detail" />
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <el-button @click="closeDialog">返 回</el-button>
      </div>
    </Drawer>
    <BaseDialog :visible.sync="followVisible" title="客档跟进" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <followModal :type="'add1'" :rowData="formData" @close="closeHandler_follow" />
    </BaseDialog>
    <Drawer :visible.sync="driveVisible" title="试驾登记" width="80%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <driveModal :type="handleType" :rowData="formData" @close="closeHandler_drive" />
    </Drawer>
    <Drawer :visible.sync="priceVisible" title="创建报价" width="80%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <quotedpriceModal :type="handleType" :rowData="formData" @close="closeHandler_price" />
    </Drawer>
    <!-- <Drawer
      :visible.sync="orderVisible"
      title="客户订单新增"
      width="80%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <priceModal :type="handleType" :rowData="formData" @close="closeHandler_order" />
    </Drawer>-->
    <!-- 选择经销商 -->
    <BaseDialog :visible.sync="visibleJXS" title="选择经销商" width="70%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <TopFilter :list="topFilterListJXS" :cols="3" labelWidth="100" @filterChange="changeHandleJXS" @onCollapse="collapseHandle"></TopFilter>
      <div class="DepartmentWrap clearfix" v-if="this.visibleJXS">
        <!-- 左侧树 -->
        <div class="leftTree">
          <span :class="sanjiao"></span>
          <el-tree :data="dataTree" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
        <!-- 右侧内容 -->
        <div class="rightContent">
          <FilterTable ref="tableJXS" :columns="columnsJXS" :dataSource="dataSource" height="auto" :onRowSelectChange="onRowSelectChange" :onColumnsChange="columns => (this.columns = columns)">
            <!-- <template slot="controls" slot-scope="props">
                <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle(props)">新增</el-button>
            </template>-->
          </FilterTable>
        </div>
      </div>
      <div style="text-align: center;margin-top: 20px;">
        <el-button size="small" type="primary" @click="confirmJSX">确定</el-button>
        <el-button size="small" type="primary" @click="cancle">关闭</el-button>
      </div>
    </BaseDialog>
  </div>
</template>

<script>
import { getFollowInfoList, getFollowInfoById, addFollowMarkup } from '@/api/potenCus/customer/customerFollowInfo';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import { exportFollow, exporturl } from '@/api/potenCus/customer/potenCusManageOEM';
import { authority } from '@/utils/authMixin';
import { formatDates } from '@/utils/validate';
import { getDataType } from '@/assets/js/auth';
import { region } from '@/api/cms-common/region'; //行政区域
import moment from 'moment';
import followModal from './followModal';
import driveModal from '../../driveManagement/driveModal';
import quotedpriceModal from '../../quotedprice/quotedpriceModal';
import priceModal from '../../../../retail/salesmanage/salesordermanage/driveModal';
import Detail from '../../potenCusManage/detail';
import { getOrgType, getDealerArea, getCompanyOrgIsMerge } from '@/api/potenCus/customer/potenCusManage';
import cluesModel from './../../potenCusManage/cluesModel';
import { getAppId } from '@/assets/js/auth';

export default {
  name: 'PotenCusManage',
  mixins: [dictionary, authority, region],
  components: {
    followModal,
    Detail,
    followModal,
    driveModal,
    quotedpriceModal,
    priceModal,
    cluesModel
  },
  props: {
    isComplete: {
      type: Number,
      default: 10041002
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    searchData: {
      type: Object,
      default: () => ({})
    },
    consultant: {
      type: Number
    },
    flag: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dataType: getDataType('dataType'),
      isShowSe: true,
      topFilterList: this.createTopFilters(),
      fetchParams: {
        isComplete: this.isComplete,
        consultant: this.consultant,
        // planActionDate: this.searchData.time || undefined,
        planActionDate: this.searchData.planActionDate ? this.searchData.planActionDate[0] : undefined || undefined,
        planActionDateEnd: this.searchData.time || undefined,
        isOverdue: this.searchData.isOverdue || undefined,
        actionStatus: this.searchData.actionStatus || undefined,
        clueType: this.searchData.clueType || undefined,
        clueStatus: this.searchData.clueStatus || undefined,
        ownerCodes: this.searchData.ownerCodes || [],
        xhrAbort: false
      },
      visible: false,
      visibleDetail: false,
      consultVisible: false,
      followVisible: false,
      driveVisible: false,
      priceVisible: false,
      orderVisible: false,
      visibleClues: false,
      // visiblePostil: false,
      formData: {},
      dialogTitle: '',
      fetchApi: getFollowInfoList,
      columns: this.createTableColumns(),
      handleType: '',
      conf: { edit: '跟进', show: '明细', postil: '批注' },
      rowstyles: [],
      cellstyles: [],
      ownerCode: '',
      dataTree: [],
      visibleJXS: false,
      topFilterListJXS: this.createTopFiltersJXS(),
      visibleJXS: false,
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      columnsJXS: this.createTableColumnsJXS(),
      dataSource: [],
      sanjiao: 'sanjiao',
      params: {
        orgId: 0,
        type: 10041002
      },
      roleType: localStorage.getItem('roleType')
    };
  },
  created() {
    this.init();
    this.isShowSelect();
  },
  methods: {
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      console.log(pl, '12342354234');
      this.topFilterList.find(item => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find(item => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
      //清除区县
      let district = this.topFilterList.find(item => item.fieldName === 'districtId');
      district.itemList = [];
      district.initialValue = '';
    },
    //初始化所在县市数据
    async initTown(cityId) {
      if (!cityId || cityId == null || typeof cityId == 'undefined') {
        return;
      }
      let td = this.cityData[cityId].children;
      let tl = this.createSubRegionList(td);
      //初始化区县，清除原值
      let district = this.topFilterList.find(item => item.fieldName === 'districtId');
      district.itemList = tl;
      district.initialValue = '';
    },
    // 导出
    async exportHandle(row) {

      let json = Object.assign({}, { CODE: 'CODE_0000020' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // let params = JSON.parse(JSON.stringify(this.fetchParams));
      // // console.log(params);

      // this.handleType = 'export';

      // await exportFollow(params)
      //   .then(response => {
      //     // console.log(response, 'response');
      //     exportExcelFile(response.data, '跟进管理');
      //     this.exportLoading = false;
      //   })
      //   .catch(err => {
      //     console.log(err);
      //   });

      // this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     exportFollow(params)
      //       .then(response => {
      //         console.log(response, 'response');
      //         exportExcelFile(response.data, '跟进管理');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     console.log('456');
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
      // }
    },

    init() {
      console.log('this.rowData', this.rowData);
      console.log(this.isComplete);
      console.log(this.dataType);
      // 查询所属顾问
      let roleType = this.dataType === 'clue' ? '10061012' : '10061012,10061015';
      this.getConsultant(1, roleType).then(result => {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = result;
      });
      if (this.isComplete == 10041003) {
        this.topFilterList.splice(2, 0, {
          type: 'SELECT',
          label: '是否完成',
          fieldName: 'isAll',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        });
      }
      //如果是厂端登录
      console.log('this.roleType:', this.roleType);
      // if (this.roleType == 10991001) {
      if (this.dataType == 10461003) {
        this.fetchParams.xhrAbort = true;
        this.topFilterList.splice(2, 0, {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerCodes',
          placeholder: '请输入',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-circle-plus" onClick={this.openDriveCancel}></el-button>;
          },
          itemList: []
        });
        if (this.isComplete == 10041001) {
          //如果是已完成
          this.topFilterList.splice(2, 0, {
            type: 'SELECT',
            label: '最新跟进',
            fieldName: 'isNewest',
            placeholder: '请选择',
            // itemList: this.createDictList('1004')
            itemList: this.createDictListRemoveCodes('1004', ['10041002'])
          });
        }
      } else {
        //如果是店端登录
        if (this.isComplete == 10041001) {
          this.fetchParams.xhrAbort = false;

          //如果是已完成
          this.topFilterList.splice(2, 0, {
            type: 'RANGE_DATE',
            label: '实际跟进时间',
            fieldName: 'factActionDate',
            placeholder: ''
          });
        }
      }
      if (this.isComplete == 10041002 && this.dataType == 10461001) {
        this.columns.find(item => item.dataIndex === 'factIntentLevel').hidden = true;
        this.columns.find(item => item.dataIndex === 'factActionDate').hidden = true;
        this.columns.find(item => item.dataIndex === 'isComplete').hidden = true;
        this.columns.find(item => item.dataIndex === 'actionedScene').hidden = true;
      }

      if (this.dataType == 10461003) {
        this.columns.splice(
          7,
          0,
          {
            title: '所属经销商',
            dataIndex: 'dealerName',
            sorter: true,
            filter: true,
            width: 150,
            align: 'center',
            filterType: 'input'
          },
          {
            title: '经销商代码',
            dataIndex: 'ownerCode',
            sorter: true,
            filter: true,
            width: 150,
            align: 'center',
            filterType: 'input'
          },
          {
            title: '所属事业部',
            dataIndex: 'orgName',
            sorter: true,
            filter: true,
            width: 150,
            align: 'center',
            filterType: 'input'
          }
        );
      }
    },

    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '关键字',
          fieldName: 'customerNameOrPhone',
          placeholder: '客户名称/手机号'
        },
        {
          type: 'RANGE_DATE',
          label: '计划跟进时间',
          fieldName: 'planActionDate',
          placeholder: ''
        },
        {
          type: 'RANGE_DATE',
          label: '线索创建时间',
          fieldName: 'businessCreatedAt',
          placeholder: ''
        },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '接触次数',
          fieldName: 'contactNumbers'
        },
        {
          type: 'SELECT',
          label: '是否逾期',
          fieldName: 'isOverdue',
          placeholder: '请选择',
          itemList: this.createDictList('7044')
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商',
        //   fieldName: 'ownerCodes',
        //   placeholder: '请输入',
        //   unitRender: () => {
        //     return <el-button slot="append" icon="el-icon-circle-plus" onClick={this.openDriveCancel}></el-button>;
        //   },
        //   itemList: []
        // },
        {
          type: 'SELECT',
          label: '线索类型',
          fieldName: 'clueType',
          placeholder: '请选择',
          itemList: this.createDictList('7019')
        },
        {
          type: 'SELECT',
          label: '订金类型',
          fieldName: 'depositType',
          placeholder: '请选择',
          itemList: this.createDictList('8050')
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initTown(props) },
        { type: 'SELECT', label: '县区', fieldName: 'districtId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'SELECT',
          label: '所属顾问',
          fieldName: 'consultants',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '跟进结果',
          fieldName: 'actionStatus',
          placeholder: '请选择',
          // itemList: this.createDictList('1517')
          itemList: this.createDictListRemoveCodes('1517', ['15171010'])
        },
        {
          type: 'SELECT',
          label: '历史客档状态',
          fieldName: 'clueStatus',
          placeholder: '请选择',
          itemList: this.createDictList('7000')
        },
        {
          type: 'SELECT',
          label: '意向级别(后)',
          fieldName: 'factIntentLevel',
          placeholder: '请选择',
          itemList: this.createDictList('1519')
        },
        {
          type: 'INPUT',
          label: '跟进备注',
          fieldName: 'taskName',
          placeholder: '请填写'
        },
        {
          type: 'SELECT',
          label: '线索评级等级',
          fieldName: 'mapClueLevel',
          hidden: getAppId() == 'beijing' ? false : true,
          placeholder: '请选择',
          itemList: [
            { value: 1, text: '一' },
            { value: 2, text: '二' },
            { value: 3, text: '三' },
            { value: 4, text: '四' },
            { value: 5, text: '五' }
          ]
        }

      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 130,
          fixed: 'left',
          render: (props, h) => {
            // <el-button size="mini" type="text" disabled={this.dataType ==10461003||props.row.actionStatus==15171005||props.row.actionStatus==15171001||props.row.customerIntentLevel==15191007||props.row.customerIntentLevel==15191006 ?true:false} onClick={() => this.editHandle(props.row)}>跟进</el-button>
            return (
              <div>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={
                    this.dataType == 10461003 ||
                      props.row.actionStatus == 15171005 ||
                      props.row.actionStatus == 15171001 ||
                      props.row.isComplete == 10041001 ||
                      props.row.customerIntentLevel == 15191007 ||
                      props.row.customerIntentLevel == 15191006
                      ? true
                      : false
                  }
                  onClick={() => this.editHandle(props.row)}
                  auth-list={this.auths}
                  auth-mark={'/api/cyxdms.clue/actioned/updateFollowRecord'}
                >
                  跟进
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </multiuse-button>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={this.dataType == 10461003 ? true : false}
                  slot="reference"
                  onClick={() => this.postilHandle(props.row)}
                  auth-list={this.auths}
                  auth-mark={'/api/cyxdms.clue/actioned/addMarkup'}
                >
                  批注
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          width: 150,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '省',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '区',
          dataIndex: 'districtName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '线索评级等级',
          dataIndex: 'mapClueLevel',
          hidden: getAppId() == 'beijing' ? false : true,
          align: 'center',
          render: props => {
            return <el-rate disabled={true} v-model={props.row.mapClueLevel}></el-rate>;
          }
        },
        {
          title: '订金类型',
          dataIndex: 'depositType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('8050'),
          render: props => {
            return <span>{this.createDictText(props.row.depositType, '8050')}</span>;
          }
        },
        {
          title: '订金金额',
          dataIndex: 'depositAmount',
          sorter: true,
          filter: true,
          width: 150,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '联系人姓名',
          dataIndex: 'contactName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          align: 'center',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '线索类型',
          dataIndex: 'clueType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7019'),
          render: props => {
            return <span>{this.createDictText(props.row.clueType, '7019')}</span>;
          }
        },
        {
          title: '来源渠道',
          dataIndex: 'clueSourceNameMax',
          sorter: true,
          filter: true,
          width: 180,
          filterType: 'input'
        },
        {
          title: '来源备注',
          dataIndex: 'sourceRemark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '意向品牌',
          dataIndex: 'intentBrandName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '意向车系',
          dataIndex: 'intentSeriesName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '意向车型',
          dataIndex: 'intentModelName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '意向配置',
          dataIndex: 'intentPackageName',
          sorter: true,
          filterType: 'input',
          width: 200
        },
        {
          title: '意向选装',
          dataIndex: 'optionName',
          sorter: true,
          filterType: 'input',
          width: 200
        },
        {
          title: '意向颜色（外饰）',
          dataIndex: 'intentColorName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '意向颜色（内饰）',
          dataIndex: 'interiorName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '线索热度',
          dataIndex: 'temperature',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
          // filterType: 'checkbox',
          // filterItems: this.createDictList('7018'),
          // render: props => {
          // return <span>{this.createDictText(props.row.temperature, '7018')}</span>;
          // }
        },
        {
          title: '意向级别(前)',
          dataIndex: 'originalLevel',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1519'),
          render: props => {
            return <span>{this.createDictText(props.row.originalLevel, '1519')}</span>;
          }
        },
        {
          title: '意向级别(后)',
          dataIndex: 'factIntentLevel',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1519'),
          hidden: false,
          render: props => {
            return <span>{this.createDictText(props.row.factIntentLevel, '1519')}</span>;
          }
        },
        {
          title: '历史客档状态',
          dataIndex: 'hisCustomerStatus',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7000'),
          render: props => {
            return <span>{this.createDictText(props.row.hisCustomerStatus, '7000')}</span>;
          }
        },
        {
          title: '是否首次跟进',
          dataIndex: 'isFirst',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isFirst, '1004')}</span>;
          }
        },
        {
          title: '接触次数',
          dataIndex: 'contactNumber',
          sorter: true,
          align: 'center',
          filterType: 'input',
          filterItems: []
        },
        {
          title: '计划跟进时间',
          dataIndex: 'planActionDate',
          sorter: true,
          align: 'center'
          // filterType: 'date-range',
          // dateFormat: 'yyyy-MM-dd',
          // render: props =>{
          //   return <span>{ formatDates(props.row.planActionDate) } </span>
          // }
        },
        {
          title: '实际跟进时间',
          dataIndex: 'factActionDate',
          sorter: true,
          align: 'center',
          hidden: false
        },
        {
          title: '跟进结果',
          dataIndex: 'actionStatus',
          sorter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1517'),
          render: props => {
            return <span>{this.createDictText(props.row.actionStatus, '1517')}</span>;
          }
        },
        {
          title: '跟进方式',
          dataIndex: 'planActionModeName',
          sorter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '是否逾期',
          dataIndex: 'isOverdue',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7044'),
          render: props => {
            return <span>{this.createDictText(props.row.isOverdue, '7044')}</span>;
          }
        },
        {
          title: '逾期时长',
          dataIndex: 'overdueTime',
          sorter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '是否完成',
          dataIndex: 'isComplete',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          hidden: false,
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isComplete, '1004')}</span>;
          }
        },
        {
          title: '所属顾问',
          dataIndex: 'consultant',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '跟进备注',
          dataIndex: 'taskName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '本次跟进情形',
          dataIndex: 'actionedScene',
          sorter: true,
          filter: true,
          hidden: false,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '线索创建时间',
          dataIndex: 'businessCreatedAt',
          sorter: true,
          align: 'center',
          hidden: false
        }
      ];
    },
    // 批注
    async postilHandle(row) {
      const res = await getFollowInfoById(row.actionId);
      // console.log('id批注明细', res.data.markup);
      this.$prompt('请输入批注内容', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        inputPattern: /^([\S\s]{1,128})$/,
        inputErrorMessage: '批注内容为1-128位',
        inputPlaceholder: '请输入批注内容',
        inputValue: res.data.markup ? res.data.markup : ''
      })
        .then(({ value }) => {
          let addData = {
            actionId: row.actionId,
            markup: value
          };
          console.log('value', value);
          if (value != null) {
            addFollowMarkup(addData).then(res => {
              console.log(res, value);
              if (res.resultCode == 200) {
                this.$message.success('批注成功!');
              }
            });
          }
        })
        .catch(() => {
          this.$message.info('取消批注!');
        });
    },
    isShowSelect() {
      if (this.dataType != 10461001) {
        this.isShowSe = false;
      } else {
        this.isShowSe = true;
      }
    },
    editHandle(row) {
      console.log('跟进', row);
      this.handleType = 'edit';
      this.ownerCode = row.ownerCode;
      this.formData = row;
      this.showEdit();
    },
    async showHandle(row) {
      console.log('跟进row明细', row);
      this.handleType = 'show';
      this.ownerCode = row.ownerCode;
      this.actionId = row.actionId;
      this.currentEditData();
      // let newRow
      // if(!row.intentLevel){
      //   row.intentLevel = row.originalLevel
      // }
      // let newRow = {
      //   ...res.data,
      //   potentialCustomersId:  res.data.customerBusinessId,
      //   potentialCustomerName: res.data.customerName,
      //   potentialCustomerPhone: res.data.mobilePhone,
      //   customerName: res.data.customerName,
      //   employeeName: res.data.consultant,
      //   customerNo: res.data.potentialCustomerNo,
      //   consultant: res.data.consultant,
      //   vehicleUse: res.data.buyCarUse,
      //   ctCode: res.data.ctCode,
      //   certificateNo: res.data.certificateNo,
      //   soStatus: 14041001,  //订单状态:未提交
      //   clueType: 70241002, // 后台确定写死
      // }
      // this.formData = newRow;
      // this.dialogTitle = `${this.conf[this.handleType]}`;
      // this.visibleDetail = true;
      // console.log(this.formData,"跟进跳转携带formData")
    },
    async currentEditData() {
      let { actionId } = this;
      const res = await getFollowInfoById(actionId, this.ownerCode);
      console.log('this.formData跟进明细', this.formData);
      let newRow = {
        ...res.data,
        potentialCustomersId: res.data.potentialCustomersId,
        potentialCustomerName: res.data.customerName,
        potentialCustomerPhone: res.data.mobilePhone,
        customerName: res.data.customerName,
        employeeName: res.data.consultant,
        customerNo: res.data.potentialCustomerNo,
        consultant: res.data.consultant,
        vehicleUse: res.data.buyCarUse,
        isComplete: res.data.isComplete,
        ctCode: res.data.ctCode ? Number(res.data.ctCode) : '',
        certificateNo: res.data.certificateNo,
        soStatus: 14041001, //订单状态:未提交
        clueType: 70241002, // 后台确定写死
        ownerCode: res.data.ownerCode
      };
      console.log('id跟进明细', res.data);
      this.formData = newRow;
      this.dialogTitle = '明细';
      this.visibleDetail = true;
      console.log(this.formData, '跟进跳转携带formData');
    },
    showEdit() {
      this.dialogTitle = `${this.conf[this.handleType]}`;
      this.visible = true;
    },
    changeHandle(val) {
      console.log('=====val====', val);
      this.fetchParams.xhrAbort = false;
      if (this.isComplete) {
        if (val.contactNumbers != null) {
          val.startContactNumber = val.contactNumbers[0];
          val.endContactNumber = val.contactNumbers[1];
        }
        if (isNaN(val.startContactNumber)) val.startContactNumber = undefined;
        if (isNaN(val.endContactNumber)) val.endContactNumber = undefined;

        this.fetchParams = Object.assign({
          isComplete: this.isComplete,
          provinceId: val.provinceId,
          cityId: val.cityId,
          districtId: val.districtId,
          customerNameOrPhone: val.customerNameOrPhone,
          taskName: val.taskName,
          mapClueLevel: val.mapClueLevel,
          startContactNumber: val.startContactNumber,
          endContactNumber: val.endContactNumber,
          planActionDate: val.planActionDate[0],
          planActionDateEnd: val.planActionDate[1],
          businessCreatedAt: val.businessCreatedAt[0],
          businessCreatedAtEnd: val.businessCreatedAt[1],
          isAll: val.isAll,
          isOverdue: val.isOverdue,
          actionStatus: val.actionStatus,
          clueType: val.clueType,
          depositType: val.depositType,
          clueStatus: val.clueStatus,
          ownerCodes: val.ownerCodes,
          factIntentLevel: val.factIntentLevel,
          consultant: val.consultants,
          isNewest: val.isNewest,
          factActionDate: val.factActionDate == null ? '' : val.factActionDate[0],
          factActionDateEnd: val.factActionDate == null ? '' : val.factActionDate[1]
        });
      } else {
        this.fetchParams = Object.assign({}, val);
      }
      // console.log(this.fetchParams)
    },
    DataHandle(data, isOverdue) {
      // console.log('data',data)
      if (!data.length) return;
      // 当天日期
      let currentDate = moment().format('YYYY-MM-DD');
      // console.log('当天日期',currentDate, new Date(currentDate))
      data.forEach(x => {
        if (x.isOverdue == 70441001 && x.isComplete == 10041002) {
          // console.log(x,"x")
          this.rowstyles.push({ row: x, styles: { background: '#FFCCCC' } });
        } else if (x.planActionDate != '' && x.isComplete == 10041002) {
          if (moment(x.planActionDate).format('YYYY-MM-DD') == currentDate || x.originalLevel == 15191005) {
            //如果跟进日期是今天或者意向级别为N，则显示黄色
            this.rowstyles.push({ row: x, styles: { background: '#FAFF69' } });
            // console.log(this.rowstyles,"x")
          }
        }
      });
    },
    // 明细的编辑
    editClick() {
      this.handleType = 'edit';
      this.visibleClues = true;
    },
    // 明细跟进
    followClick() {
      this.handleType = 'add1';
      this.followVisible = true;
    },
    // 明细的试驾
    driveClick() {
      this.handleType = 'add';
      this.driveVisible = true;
    },
    // 明细的报价
    offerClick() {
      this.handleType = 'add';
      this.priceVisible = true;
    },
    // 明细的下单
    orderClick() {
      this.handleType = 'add';
      this.orderVisible = true;
    },
    closeHandler_clues(val, type) {
      this.visibleClues = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_detail(val, type) {
      this.visibleDetail = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_follow(val, type) {
      this.followVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.currentEditData();
        this.fetchParams = { ...this.fetchParams };
        this.$refs.Detail.tabRefresh();
      }
    },
    closeHandler_drive(val, type) {
      this.driveVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_price(val, type) {
      this.priceVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_order(val, type) {
      this.orderVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeDialog() {
      this.visibleDetail = false;
    },
    fatherClose(val, type) {
      console.log('跟进并编辑来的值', val);
      this.visible = false;
      this.formData = val.data;
      this.formData.clueType = 70241002;
      if (val.data.actionStatus === 15171005 || val.data.actionStatus === 151710057 || val.data.actionStatus === 151710059) {
        this.$message.info('当前客档不可编辑');
        return;
      } else {
        this.visibleClues = true;
      }
      this.dialogTitle = `客档管理编辑`;
      this.fetchParams = { ...this.fetchParams };
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },

    //经销商
    openDriveCancel() {
      this.visibleJXS = true;
      this.topFilterList.find(item => item.fieldName == 'ownerCodes').initialValue = '';
      this.dataSourceList = '';
      this.getVueTree();
    },
    // getVueTree
    async getVueTree() {
      this.dataTree = [];
      // 当前经销商有无小区 是否合并
      const res = await getCompanyOrgIsMerge();
      console.log('是否合并', res);
      // isDisArea： 10041001 只有大区   10041002 ：有小区
      // isMerge ：10041001 销售售后合并  10041002 ：不合并
      let { isDisArea, isMerge } = res.data;
      // 1. 不合并只大区 传15061005
      if (isDisArea == 10041001 && isMerge == 10041002) {
        // 查询经销商代码
        const res1 = await getOrgType(15061005);
        console.log('经销商代码1', res1.data);
        if (res1.resultCode == 200) {
          this.dataTree = res1.data.map(x => ({ value: x.orgId, text: x.orgName }));
        }
      }
      // 2. 不合并大小区 传15061005 ,15061007
      if (isDisArea == 10041002 && isMerge == 10041002) {
        let orgType1 = '15061005';
        const res2 = await getOrgType(orgType1);
        console.log('经销商代码2', res2);
        if (res2.resultCode == 200) {
          this.dataTree = res2.data.map(x => ({ value: x.orgId, text: x.orgName, orgType: x.orgType, children: [] }));
        }
      }
      // 3. 合并大区 传15061004
      if (isDisArea == 10041001 && isMerge == 10041001) {
        const res3 = await getOrgType(15061014);
        console.log('经销商代码3', res3);
        if (res3.resultCode == 200) {
          this.dataTree = res3.data.map(x => ({ value: x.orgId, text: x.orgName }));
        }
      }
      // 4. 合并大小区 传15061014， 15061015
      if (isDisArea == 10041002 && isMerge == 10041001) {
        let orgType2 = '15061014';
        const res4 = await getOrgType(orgType2);
        console.log('经销商代码4', res4);
        if (res2.resultCode == 200) {
          this.dataTree = res4.data.map(x => ({ value: x.orgId, text: x.orgName, orgType: x.orgType, children: [] }));
        }
      }
    },
    createTopFiltersJXS() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入'
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        }
      ];
    },
    //选择进销商
    changeHandleJXS(val) {
      console.log('123', val);
      getDealerArea('', val.dealerCode ? val.dealerCode : '', val.dealerName ? val.dealerName : '').then(res => {
        console.log('根据事业部查询经销商', res);
        this.dataSource = [];
        if (res.resultCode === 200) {
          this.dataSource = res.data.map((x, k) => ({ index: k, dealerCode: x.dealerCode, dealerName: x.dealerName }));
        }
      });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    preDictList(codes = []) {
      let { createDictList } = this;
      return this.flatten(codes.map(item => createDictList(item)));
    },
    flatten(list) {
      while (list.some(Array.isArray)) {
        list = [].concat(...list);
      }
      return list;
    },
    //确定
    confirmJSX() {
      console.log(this.dataSourceList, 'this.dataSourceList');
      this.topFilterList.find(item => item.fieldName == 'ownerCodes').initialValue = '';
      if (this.dataSourceList) {
        this.topFilterList.find(item => item.fieldName == 'ownerCodes').initialValue = this.dataSourceList;
        this.visibleJXS = false;
        this.params.orgId = 0;
        this.params.type = 10041002;
      } else {
        this.$message({
          type: 'info',
          message: '请选择一条数据'
        });
      }
    },
    //关闭
    cancle() {
      this.visibleJXS = false;
      this.params.orgId = 0;
      this.params.type = 10041002;
    },
    //树节点
    handleNodeClick(data) {
      this.sanjiao = '';
      console.log(data, 'data');
      if (data != '' || data != 'undefined') {
        this.params.orgId = data.value;
        if (data.orgType && data.orgType == '15061005') {
          getOrgTypeForMin(data.value, 15061007).then(res => {
            console.log(res, '小区15061007');
            data.children = res.data;
          });
        } else if (data.orgType && data.orgType == '15061014') {
          getOrgTypeForMin(data.value, 15061015).then(res => {
            console.log(res, '小区15061015');
            data.children = res.data;
          });
        } else {
          getDealerArea(data.value, '', '').then(res => {
            console.log('根据事业部查询经销商', res);
            if (res.resultCode === 200) {
              this.dataSource = res.data.map((x, k) => ({ index: k, dealerCode: x.dealerCode, dealerName: x.dealerName }));
            }
          });
        }
      }
    },
    createTableColumnsJXS() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          filterType: 'input',
          filterItems: [],
          editable: false
          // editType: 'select',
          // editItems: this.createDictList('7021')
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          filterType: 'input',
          filterItems: [],
          editable: false
          // editType: 'select',
          // editItems: []
        }
      ];
    },
    //表格数据变化时
    onRowSelectChange(row) {
      console.log(row, 'val');
      if (row && row.length == 1) {
        row.map(x => {
          this.dataSourceList = x.dealerCode;
        });
      } else {
        this.dataSourceList = '';
        row.map(x => {
          this.dataSourceList += x.dealerCode + ',';
        });
      }
    }
  },
  mounted() {
    this.initProvince();
    if (10461003 == this.dataType) {
      this.topFilterList.find(item => item.fieldName === 'consultants').hidden = true;
    }
    this.BaseTable = this.$refs.table.$refs.pageTable;
    //首页报表进入

    if (this.searchData.planActionDate) {
      this.topFilterList.find(item => item.fieldName === 'planActionDate').initialValue = this.searchData.planActionDate;

      // setTimeout(() => {
      //   this.$refs.TopFilter.SUBMIT_FORM()
      // },400);
    }
    if (this.searchData.isOverdue) {
      this.topFilterList.find(item => item.fieldName === 'isOverdue').initialValue = this.searchData.isOverdue;
    }
    if (this.consultant && this.flag == 1) {
      this.topFilterList.find(item => item.fieldName === 'consultants').initialValue = this.consultant;
    }
  }
};
</script>

<style lang="less" scoped>
.father {
  width: 380px;
  height: auto;
  position: relative;
  float: right;
}
.son {
  position: absolute;
  top: -5px;
  right: 10px;
  z-index: 2;
}
.sanjiao {
  position: absolute;
  left: 18px;
  top: 19px;
  z-index: 99;
  width: 0;
  height: 0;
  border-top: 3px solid transparent;
  border-bottom: 5px solid transparent;
  border-left: 9px solid #ccc;
}
.DepartmentWrap {
  // height: 79vh;
  height: 26vw;
  border: 1px solid #000;
  box-sizing: border-box;
  overflow: hidden;
  .leftTree {
    width: 36%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    float: left;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
  }

  .rightContent {
    width: 64%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;
    float: left;
    box-sizing: border-box;
    padding: 10px;
    border-left: 2px solid #eee;
  }
}
</style>
